package base

import (
	log "github.com/sirupsen/logrus"
	"net/http"
	"time"
)

var httpServer *http.Server
var handler http.Handler

//全局配置管理实例
func HttpHandler() http.Handler {
	Check(handler)
	return handler
}
func SetHttpHandler(h http.Handler) {
	Check(h)
	handler = h
}

//全局配置管理实例
func HttpServer() *http.Server {
	Check(httpServer)
	return httpServer
}

type HttpServerStarter struct {
	BaseStarter
	port       string
	httpServer *http.Server
}

func (s *HttpServerStarter) Init(ctx StarterContext) {
	s.port = ctx.Props().GetDefault("app.server.port", "8080")
	addr := ":" + s.port
	handler = http.NewServeMux()
	s.httpServer = &http.Server{
		Addr:         addr,
		WriteTimeout: time.Second * 4,
		Handler:      handler,
	}
	httpServer = s.httpServer
}

func (s *HttpServerStarter) Setup(ctx StarterContext) {}
func (s *HttpServerStarter) Start(ctx StarterContext) {
	outAddr := "0.0.0.0:" + s.port
	log.Info("http server listening on: ", outAddr)
	err := HttpServer().ListenAndServe()
	if err != nil {
		if err == http.ErrServerClosed {
			log.Fatal("Server closed under request")
		} else {
			log.Fatal("Server closed unexpected", err)
		}
	}
}

func (s *HttpServerStarter) StartBlocking() bool { return true }
func (s *HttpServerStarter) Stop(ctx StarterContext) {
	if err := httpServer.Close(); err != nil {
		log.Fatal("Close server:", err)
	}
}
